package com.java.dao.impl;

import com.java.bean.Admin;
import com.java.dao.BaseAdminDao;
import com.java.util.DBUtil;
import com.java.util.DateUtil;
import com.java.util.DruidUtil;

import java.sql.*;

public class AdminDaoMysql extends DBUtil implements BaseAdminDao {// language=MySQL
    private static final String SQL_LOGIN = "SELECT * FROM admins WHERE name=? AND password=?";// language=MySQL
    private static final String SQL_UPDATE_LOGINTIME_AND_IP = "UPDATE admins SET logintime=?,ip=? WHERE name=?";// language=MySQL
    private static final String SQL_GET_ADMIN_BY_NAME = "SELECT * FROM admins WHERE NAME=?";

    /**
     * 管理员登录，判断账号是否存在
     *
     * @param admin 账号名和密码
     * @return true 账号存在，false 账号不存在
     */
    @Override
    public Admin login(Admin admin) {
        connection = DruidUtil.getConnection();
        if (connection == null) {
            throw new RuntimeException("connection is null!");
        }
        Admin a;
        try {
            pps = connection.prepareStatement(SQL_LOGIN);
            pps.setString(1, admin.getName());
            pps.setString(2, admin.getPassword());
            rs = pps.executeQuery();
            a = setOne(Admin.class);
            if (a != null) {
                updateLoginTimeAndIP(admin.getName(), admin.getLogintime(), admin.getIp());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            closeAll();
        }
        return a;
    }

    /**
     * 通过管理员的账号名获取管理员的信息
     *
     * @param adminName 管理员的账号名
     * @return 管理员的信息，没有则返回 null
     */
    @Override
    public Admin getAdmin(String adminName) {
        try {
            query(pps(SQL_GET_ADMIN_BY_NAME), adminName);
            return setOne(Admin.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return null;
    }

    /**
     * 更新管理员的登录时间和登录的 ip 地址
     *
     * @param adminName 账号名
     * @param timestamp 登录时间
     * @param ip        ip 地址
     * @return 影响行数
     */
    @Override
    public int updateLoginTimeAndIP(String adminName, Timestamp timestamp, String ip) {
        final Connection conn = DruidUtil.getConnection();
        if (conn == null) {
            throw new RuntimeException("connection is null!");
        }
        try {
            final PreparedStatement pps = conn.prepareStatement(SQL_UPDATE_LOGINTIME_AND_IP);
            pps.setString(1, DateUtil.format(timestamp));
            pps.setString(2, ip);
            pps.setString(3, adminName);
            return pps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
